package com.ferry.id.snowflake;

import com.ferry.id.common.IdGenetator;
import com.ferry.id.common.IpUtils;
import com.ferry.id.common.Result;
import com.ferry.id.common.Status;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

/**
 * Created by daiyong
 */
public class SnowflakeIdGenerator implements IdGenetator {

	private static final Logger LOGGER = LoggerFactory.getLogger(SnowflakeIdGenerator.class);

	private long workerId;
	private long sequence = 0L;
	private long lastTimestamp = -1L;
	private static final Random RANDOM = new Random();
	private final long twepoch;
	private final long sequenceBits = 12L;
	private final long workerIdBits = 10L;
	private final long workerIdShift = sequenceBits;
	private final long timestampLeftShift = sequenceBits + workerIdBits;
	private final long sequenceMask = ~(-1L << sequenceBits);

	public SnowflakeIdGenerator(String zkAddress, String port, long twepoch) {
		this.twepoch = twepoch;
		final String ip = IpUtils.getIp();
		ZkHolder holder = new ZkHolder(ip, String.valueOf(port), zkAddress);
		boolean initFlag = holder.init();
		if (initFlag) {
			workerId = holder.getWorkerID();
		} else {
			Preconditions.checkArgument(initFlag, "Snowflake Id Gen is not init ok");
		}
	}


	@Override
	public synchronized Result getId(String key) {

		long timestamp = timeGen();

		if (timestamp < lastTimestamp) {
			long offset = lastTimestamp - timestamp;
			if (offset <= 5) {
				try {
					wait(offset << 1);
					timestamp = timeGen();
					if (timestamp < lastTimestamp) {
						return new Result(-1, Status.FAIL);
					}
				} catch (InterruptedException e) {
					return new Result(-2, Status.FAIL);
				}
			} else {
				return new Result(-3, Status.FAIL);
			}
		}
		if (lastTimestamp == timestamp) {
			sequence = (sequence + 1) & sequenceMask;
			if (sequence == 0) {
				//seq 为0的时候表示是下一毫秒时间开始对seq做随机
				sequence = RANDOM.nextInt(100);
				timestamp = tilNextMillis(lastTimestamp);
			}
		} else {
			//如果是新的ms开始
			sequence = RANDOM.nextInt(100);
		}
		lastTimestamp = timestamp;
		long id = ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
		return new Result(id, Status.SUCCESS);
	}

	protected long tilNextMillis(long lastTimestamp) {
		long timestamp = timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = timeGen();
		}
		return timestamp;
	}

	protected long timeGen() {
		return System.currentTimeMillis();
	}

	@Override
	public boolean init() {
		return true;
	}
}
